﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Goods;
using Traceable.App.DTOS;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Goods
{
    /// <summary>
    ///根据Id获取商品详情处理层
    /// </summary>
    public class GetGoodsDetailHandler : IRequestHandler<GetGoodsDetailCommand, ApiResult<GoodsTraceableDto>>
    {
        private readonly IBaseRepository<Traceable_Table> _traceableRepository;
        private readonly IBaseRepository<Goods_Table> _goodsRepository;
        private readonly IMapper _mapper;

        public GetGoodsDetailHandler(IBaseRepository<Traceable_Table> traceableRepository, IBaseRepository<Goods_Table> goodsRepository, IMapper mapper)
        {
            _traceableRepository = traceableRepository;
            _goodsRepository = goodsRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<GoodsTraceableDto>> Handle(GetGoodsDetailCommand request, CancellationToken cancellationToken)
        {
            ApiResult<GoodsTraceableDto> result = new ApiResult<GoodsTraceableDto>();

            var goods = _goodsRepository.GetAll();
            var traceable = _traceableRepository.GetAll().Where(p=>p.Id==request.Id);

            var list =( from t in traceable join g in goods on t.GoodsId equals g.Id
                       select new GoodsTraceableDto
                       {
                           Id = t.Id,
                           GoodsId = g.Id,
                           GoodsName = g.GoodsName,
                           Batch = t.Batch,
                           Expiration = t.Expiration,
                           Permit = t.Permit,
                           Companies = t.Companies,
                           Perfect = t.Perfect,
                           Cover = t.Cover,
                           CreateTime = t.CreateTime,
                           Creater = t.Creater,
                           UpdateTime = t.UpdateTime,
                           Updater = t.Updater
                       }).FirstOrDefault();
            result.Code = StatusEnum.OK;
            result.Data =list;
            result.Message = "获取商品详情成功";
            return Task.FromResult(result);

        }
    }
}
